#!/usr/bin/env python
from math import *

sr_1=887.1e6;
#sr_1=900e6; #sending rate for flow 1
sr_2=297e6;
#sr_2=99e6;
#sr_2=300e6; #sending rate for flow 2
pkt_size=12000;
Q_max=10; #max queue size
sevice_rate = 978.24e6;
#st=pkt_size/sevice_rate;
st=13e-6;
#st=18e-6; #baseline service time for a packet
#starting_time=30.0e-6;
starting_time=0.0;

r=0.0; #time when scheduling current round
prev_r=0.0; #time when scheduling current round
prev_prev_r=0.0;
A_1=0; # queue 1, number of frames arrived during a time period
A_2=0; # queue 2, number of frames arrived during a time period
Q_1=0; #queue 1, size at time t
Q_2=0; #queue 2, size at time t
N=0; #frames scheduled in current round
N_1=0; #queue 1, frames scheduled in current round
N_2=0; #queue 2, frames scheduled in current round
L_1=0; #queue 1, frames left in the queue (no scheduled) in current round
L_2=0; #queue 2, frames left in the queue (no scheduled) in current round
#prev_L_1; #queue 1, frames left in the queue (no scheduled) in current round
#prev_L_2; #queue 2, frames left in the queue (no scheduled) in current round

fh1 = open("/Volumes/Data/gSVN/ethernet-switch/script/simulation/900_300_r.txt", "w")
fh2 = open("/Volumes/Data/gSVN/ethernet-switch/script/simulation/900_300_q1.txt", "w")
fh3 = open("/Volumes/Data/gSVN/ethernet-switch/script/simulation/900_300_q2.txt", "w")

#r0 and r1
r=starting_time;
#print "r=%f, q_1=1, q_2=0\n"%(r);
#prev_r=r;

#N=1;
#r=prev_r+st*N;
#print "r=%f, q_1=0, q_2=1\n"%(r);
#prev_prev_r=prev_r;
#prev_r=r;

prev_prev_r=starting_time;
#prev_r=41e-6;
prev_r=pkt_size/min(sr_1,sr_2)+1e-6+starting_time;

#compute r after r1
for i in range(1, 1000):

	A_1=min((prev_r-prev_prev_r)*sr_1/pkt_size, Q_max-L_1);
	A_2=min((prev_r-prev_prev_r)*sr_2/pkt_size, Q_max-L_2);
	
	#print "A_1 %d, A_2 %d, L_1 %d, L_2 %d, prev_r %f, prev_r_r %f, sr_1 %f, pkt_size %d, Q_max %d\n"%(A_1, A_2, L_1, L_2, prev_r, prev_prev_r, sr_1, pkt_size, Q_max);
	
	the_min=min(A_1+L_1, A_2+L_2);
	N_1=(int)(A_1+L_1)/(int)(the_min);
	N_2=(int)(A_2+L_2)/(int)(the_min);
	
	N=N_1+N_2;
	
	r=prev_r+st*N;
	
	Q_1=A_1+L_1;
	Q_2=A_2+L_2;
	
	#print "the_min %d, N_1 %d, N_2 %d, N %d, r %f, Q_1 %d, Q_2 %d\n"%(the_min, N_1, N_2, N, r, Q_1, Q_2);	
	print "r %f, q_1 %d, q_2 %d\n"%(r, Q_1, Q_2);
	str_r="%.6f" % r;
	fh1.write (str_r);fh1.write (", ");
	str_q1="%d" % Q_1;
	fh2.write (str_q1);fh2.write (", ");
	str_q2="%d" % Q_2;
	fh3.write (str_q2);fh3.write (", ");
	
	prev_prev_r=prev_r;
	prev_r=r;
	L_1=Q_1-N_1;
	L_2=Q_2-N_2;
	



#num_delay_given_loss = [0]*(max_array_length);

#I/O
#fi = open("/Volumes/Data/gSVN/ethernet-switch/script/simulation/900_700_arrival_time.txt", "r");
#fh.write(out);

#fi.close();
fh1.close();
fh2.close();
fh3.close();